package com.yanwq.sayhi.base;

import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

import com.yanwq.sayhi.R;
import com.yanwq.sayhi.widget.MProgressDialog;

/**
 * 作者：yanweiqiang。
 * 日期：2016/2/29 11:25。
 */
public class BaseDialogFragment extends DialogFragment {
    private MProgressDialog mProgressDialog;

    public BaseDialogFragment() {
        super();
        setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogFragment);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                dismissAllowingStateLoss();
                return true;
            }
        });

        mProgressDialog = new MProgressDialog(getActivity());

        translucentWindow();
    }

    public MProgressDialog getProgressDialog() {
        return mProgressDialog;
    }

    public void showProgressDialog(String prompt) {
        mProgressDialog.setMessage(prompt);
        mProgressDialog.show();
    }

    public void cancelProgressDialog() {
        mProgressDialog.cancel();
    }

    public View findViewById(int res) {
        assert getView() != null;
        return getView().findViewById(res);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.getWindow().getAttributes().windowAnimations = R.style.DialogFragment;
        return dialog;
    }

    private void translucentWindow() {
        WindowManager.LayoutParams params = getDialog().getWindow().getAttributes();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            params.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        } else {
            params.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
        }
        getDialog().getWindow().setAttributes(params);
    }

    public void post(Runnable runnable) {
        if (getView() != null) {
            getView().post(runnable);
        } else {
            throw new NullPointerException("Fragment root view is null!");
        }
    }

    public void post(Runnable runnable, int delayMillis) {
        if (getView() != null) {
            getView().postDelayed(runnable, delayMillis);
        } else {
            throw new NullPointerException("Fragment root view is null!");
        }
    }
}
